<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="字典名称" prop="dictType">
        <el-select v-model="queryParams.dictType" style="width: 240px" placeholder="请选择字典类型" clearable>
          <el-option v-for="item in typeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictType" />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel" style="width: 240px">
        <el-input v-model="queryParams.dictLabel" placeholder="请输入字典标签" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable style="width: 240px">
          <el-option v-for="item in dict.type.sys_normal_disable" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd" v-p="['system:dict:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="ids.length > 1 || ids.length === 0"
          @click="handleUpdate"
          v-p="['system:dict:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="ids?.length === 0" @click="handleDelete" v-p="['system:dict:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleClose">关闭</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编码" align="center" prop="dictCode" />
      <el-table-column label="字典标签" align="center" prop="dictLabel">
        <template v-slot="scope">
          <span
            v-if="
              (scope.row.listClass == '' || scope.row.listClass == 'default') &&
              (scope.row.cssClass == '' || scope.row.cssClass == null)
            "
          >
            {{ scope.row.dictLabel }}
          </span>
          <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass" :class="scope.row.cssClass">
            {{ scope.row.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="字典排序" align="center" prop="dictSort" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag type="" v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)" v-p="['system:dict:edit']">修改</el-button>
          <el-button type="primary" link @click="handleDelete(scope.row)" v-p="['system:dict:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getDictDataList"
    />
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in dict.type.sys_normal_disable" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import type { DictTypeEntry } from "@/typings";
import {
  addDictDataApi,
  delDictDataApi,
  getDictDataByDictCodeApi,
  getDictDataListApi,
  getDictTypeInfoApi,
  getDictTypeOptionSelectApi,
  updateDictDataApi
} from "@/api";
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import { useTabsStore } from "@/stores";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/pagination/Pagination.vue";

// 路由和标签页状态
const route = useRoute();
const useTabs = useTabsStore();

// 查询表单及其参数
const queryForm = ref<FormInstance>();
const queryParams = ref({
  dictType: "",
  dictLabel: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 表单及其验证规则
const formRef = ref<FormInstance>();
const form = ref<DictTypeEntry | any>({
  dictType: "",
  dictLabel: "",
  dictValue: "",
  cssClass: "",
  dictSort: 0,
  listClass: "default",
  status: "0",
  remark: ""
});

const rules = reactive<any>({
  dictLabel: [
    { required: true, message: "请输入字典标签", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
  ],
  dictValue: [
    { required: true, message: "请输入字典键值", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
  ],
  cssClass: [{ min: 0, max: 100, message: "长度在 0 到 100 个字符", trigger: "blur" }],
  dictSort: [
    { required: true, message: "请输入字典排序", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  listClass: [{ required: true, message: "请选择显示样式", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  remark: [{ min: 0, max: 200, message: "长度在 0 到 200 个字符", trigger: "blur" }]
});

// 其他状态及数据
const ids = ref<number[]>([]);
const open = ref(false);
const title = ref("新增字典数据");
const loading = ref(false);
const dataList = ref([]);
const total = ref(0);
const typeOptions = ref<DictTypeEntry[]>([]);

const dict: { type: { sys_normal_disable: { value: string; label: string }[] } } = {
  type: {
    sys_normal_disable: [
      { value: "0", label: "正常" },
      { value: "1", label: "停用" }
    ]
  }
};

// 显示样式选项
const listClassOptions = ref([
  { value: "default", label: "默认" },
  { value: "primary", label: "主要" },
  { value: "success", label: "成功" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" }
]);

// 选择变化处理
const handleSelectionChange = (data: DictTypeEntry[]) => {
  ids.value = data.map((item: DictTypeEntry) => item.dictCode);
};

// 新增字典数据处理
const handleAdd = () => {
  formRef.value?.resetFields();
  form.value = {};
  form.value.dictType = queryParams.value.dictType;
  title.value = "新增字典数据";
  open.value = true;
};

// 修改字典数据处理
const handleUpdate = async (row: DictTypeEntry | any) => {
  try {
    title.value = "修改岗位";
    const dictCode = row.dictCode || ids.value?.join(",");
    const res = await getDictDataByDictCodeApi(dictCode);
    if (res.code === 200) {
      form.value = { ...res.data };
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("修改字典数据失败");
  }
  open.value = true;
};

// 删除字典数据处理
const handleDelete = (row: DictTypeEntry | any) => {
  try {
    if (ids.value?.length) {
      row.dictCode = ids.value.join(",");
    }
    ElMessageBox.confirm("确定删除所勾选的字典数据吗？删除之后数据将无法恢复", "系统提示", {
      type: "warning"
    }).then(async () => {
      const res = await delDictDataApi(row.dictCode);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getDictDataList();
      } else {
        ElMessage.error(res.message);
      }
    });
  } catch (error) {
    ElMessage.error(error as string);
  }
};

const handleClose = () => {
  // 关闭当前页面
  const currentPath = route.path;
  useTabs.closeTab(currentPath, true);
};

// 查询数据处理
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getDictDataList();
};

// 重置查询条件
const resetQuery = () => {
  queryForm.value?.resetFields();
  queryParams.value.dictType = defaultDictType.value as string;
  getDictDataList();
};

// 新增字典数据的API处理
const addDictData = async (data: DictTypeEntry) => {
  try {
    const res = await addDictDataApi(data);
    if (res.code === 200) {
      ElMessage.success("新增字典数据成功");
      formRef.value?.resetFields();
      open.value = false;
      getDictDataList();
      formRef.value?.resetFields();
      Object.assign(form.value, {});
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("新增字典数据失败");
  }
};

// 修改字典数据的API处理
const updateDictData = async (data: DictTypeEntry) => {
  try {
    const res = await updateDictDataApi(data);
    if (res.code === 200) {
      ElMessage.success("修改字典数据成功");
      open.value = false;
      getDictDataList();
      formRef.value?.resetFields();
      Object.assign(form.value, {});
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("修改字典数据失败");
  }
};

// 表单提交处理
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if (form.value.dictCode) {
        // update
        updateDictData(form.value);
      } else {
        // add
        addDictData(form.value);
      }
    } else {
      console.error("error submit!", fields);
    }
  });
};

// 取消操作
const cancel = () => {
  formRef.value?.resetFields();
  Object.assign(form.value, {});
  open.value = false;
};

// 获取字典类型信息
const defaultDictType = ref<string>();
const getDictTypeInfo = async () => {
  const dictId = route.params && (route.params.dictId as string);
  try {
    const res = await getDictTypeInfoApi(dictId);
    if (res.code === 200) {
      queryParams.value.dictType = res.data.dictType;
      defaultDictType.value = res.data.dictType;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("获取字典类型信息失败");
  }
};

// 获取字典数据列表
const getDictDataList = async () => {
  try {
    loading.value = true;
    const res = await getDictDataListApi(queryParams.value);
    if (res.code === 200) {
      dataList.value = res.data;
      total.value = res.total as number;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("获取字典数据列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取字典类型下拉选项
const getDictTypeOptionSelect = async () => {
  try {
    const res = await getDictTypeOptionSelectApi();
    if (res.code === 200) {
      typeOptions.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("获取字典类型下拉选项失败");
  }
};

// 组件挂载时的初始化操作
onMounted(async () => {
  await getDictTypeInfo();
  await getDictDataList();
  await getDictTypeOptionSelect();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
